package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.TagDao;
import com.leoman.entity.Tag;
import com.leoman.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * TagServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:01.
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagDao tagDao;

    @Override
    public List<Tag> findAll() {
        return tagDao.findAll();
    }

    @Override
    public Page<Tag> find(int pageNum, int pageSize) {
        return tagDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Tag> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Tag getById(int id) {
        return tagDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        tagDao.delete(id);
    }

    @Override
    public Tag create(Tag tag) {
        return tagDao.save(tag);
    }

    @Override
    public Tag update(Tag tag) {
        return tagDao.save(tag);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Integer save(Integer tagId, String content) {
        try {
            Tag tag;
            if (null == tagId) {
                tag = new Tag();
            } else {
                tag = tagDao.findOne(tagId);
                tag.setUpdateTime(System.currentTimeMillis());
            }

            tag.setContent(content);

            tagDao.save(tag);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}